package com.gmgz.controller;

import com.gmgz.config.SystemConfig;
import com.gmgz.interceptor.AdminInterceptor;
import com.gmgz.model.News;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;

import java.util.Date;

@Before(AdminInterceptor.class)
public class NewsController extends Controller {
	
	public void index() {
		int page = getParaToInt("page", 1);
        int type = getParaToInt("type", 1);
		Page<News> pageRecord = News.me.paginate(page, SystemConfig.getInstance().getPageSize(), "select *", "from news where type=? order by createTime desc", type);
			
		setAttr("pageRecord", pageRecord);
        setAttr("type", type);
		
		renderJsp("index.jsp");
	}

	public void renderIndex(int type) {
		Page<News> pageRecord = News.me.paginate(1, SystemConfig.getInstance().getPageSize(), "select *", "from news where type=? order by createTime desc", type);

		setAttr("pageRecord", pageRecord);
		setAttr("type", type);

		renderJsp("index.jsp");
	}
	
	public void form() {
		Integer id = getParaToInt("id");
		if(id != null && id > 0) {
			// 更新
			setAttr("news", News.me.findById(id));
		}
		
		render("form.jsp");
	}
	
	public void view() {
		News news = News.me.findById(getParaToInt("id"));
		
		if(news != null) {
			// 浏览次数+1
			news.set("clicks", news.getInt("clicks") + 1);
			news.update();
			
			setAttr("news", news);
			renderJsp("view.jsp");
		} else {
			renderText("加载文章内容失败");
		}
	}

    public void create() {
        int type = getParaToInt("type");
		News news = new News();
		news.set("type", type);
        setAttr("news", news);
        renderJsp("form.jsp");
    }
	
	public void save() {
		News news = getModel(News.class, "news");
		if(news.get("id") == null) {
			// 新增
			news.set("createTime", new Date());
			news.set("clicks", 1);
			news.save();
		} else if(news.getInt("id") > 0) {
			// 更新
			news.update();
		}

		renderIndex(news.getInt("type"));
	}
	
	public void delete() {
		Integer id = getParaToInt("id");
		if(id != null && id > 0) {
			boolean flag = News.me.deleteById(id);
			if(flag) {
				index();
			} else {
				renderText("删除新闻失败");
			}
		} else {
			renderText("删除新闻失败");
		}
	}

}
